package com.example.authforcmcc;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import cc.ufinity.networkdiagnose.app.AppLogs;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.MessageWhat;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AuthForCmcc {

	/** 用户名 */
	private String userName = "";
	/** 密码 */
	private String passWord = "";
	/** webView组件 */
	private WebView webView;
	/** 用来传递消息的hanlder */
	private Handler cmccHandler;
	/** 这个是用来开始测试的handler */
	private Handler mhandler;
	/*** WEB所需要依附的Activity,认证界面传递过来的 */
	private Activity ctx;
	/** 访问百度返回的字符串 */
	private String AuthString = "";
	private boolean isSuccess = false;
	private HttpClient client;

	private WifiManager wifiManager;
	private WifiInfo wifiInfo = null;
	
	private boolean isFirst;
	
	private float loadAuthTime = 0;
	private long loadAuthStartTime = 0;
	private long loadAurhEndTime = 0;

	public AuthForCmcc(Activity content, Handler Nhandler, String Name,
			String PassWord) {
		this.ctx = (Activity) content;
		this.cmccHandler = Nhandler;
		this.userName = Name;
		this.passWord = PassWord;

		client = HttpUtils.getSSLHttpClient();

		webView = new WebView(ctx);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
		webView.setWebViewClient(new MyWebViewClient());
		
		wifiManager = (WifiManager) ctx.getSystemService(ctx.WIFI_SERVICE);
		wifiInfo = wifiManager.getConnectionInfo();

		isFirst = true;
		
		mhandler = new Handler() {
			public void handleMessage(Message msg) {
				
				switch (msg.arg1) {
				case MessageWhat.BAIDU_LOADED:// 访问百度得到了全部的源码之后开始认证
					System.out.println("认证页面：-----------"+AuthString);
					new Thread(){
						public void run() {
							if (authToCMCC(AuthString, userName, passWord)) {// 上线成功
								System.out.println("suce===========");
								Message msg1 = new Message();
								msg1.what = MessageWhat.LOGIN_SUCCESS;
								cmccHandler.sendMessage(msg1);
							} else { // 上线失败
								System.out.println("失败e===========");
								Message msg2 = new Message();
								msg2.what = MessageWhat.LOGIN_FAILED;
								cmccHandler.sendMessage(msg2);
							}
						}
					}.start();
					break;
				}
			}
		};
	}

	public void startAutuByPra() {
		new Thread() {
			public void run() {
				if (authToCMCC(Global.AuthString, userName, passWord)) {// 上线成功
					System.out.println("suce===========");
					Message msg1 = new Message();
					msg1.what = MessageWhat.LOGIN_SUCCESS;
					cmccHandler.sendMessage(msg1);
				} else { // 上线失败
					System.out.println("失败e===========");
					Message msg2 = new Message();
					msg2.what = MessageWhat.LOGIN_FAILED;
					cmccHandler.sendMessage(msg2);
				}
			}
		}.start();
	}
	
	public void startAuth() {
		if (Global.AuthString!=null) {
			startAutuByPra();
		}else {
			new Thread() {
				public void run() {
					System.out.println("加载baidu");
					loadAuthStartTime = System.currentTimeMillis();
					webView.loadUrl("http://www.baidu.com");
				}
			}.start();
		}
	}

	
	/**
	 * CMCC的上线
	 * 
	 * @param result
	 * @param userName
	 * @param strPassWord
	 * @return
	 */
	@SuppressWarnings("finally")
	public boolean authToCMCC(String result, String userName, String strPassWord) {
		boolean isSuccess = false;
		this.userName = userName;
		this.passWord = strPassWord;
		HttpResponse response = null;
		if (!result.contains("找不到网页")  && result.contains("百度")) {
			return true;
		}else if(result.contains("找不到网页")){
			AppLogs.logData += "\n 认证未跳转到认证页，返回找不到网页错误";
		}
		try {
			HttpClient client = HttpUtils.getSSLHttpClient();

			Map<String, String> mapParas = parseParamst(result, "input");// 获取hidden的参数
			// https://221.176.1.140:8090/wlan/login.do
			// /https://221.176.1.140:8090
			String dologinUrl = logingdo(result, "form", "action");
			System.out.println("登录的地址---------CMCC---------------》：" + dologinUrl);
			HttpPost post = new HttpPost(dologinUrl);
			try {
				post.setEntity(new UrlEncodedFormEntity(setRequestParams(mapParas)));// 设置请求参数
				response = client.execute(post);
				result = EntityUtils.toString(response.getEntity());
			} catch (Exception e) {
				
				StringWriter sw = new StringWriter();
				e.printStackTrace(new PrintWriter(sw, true));
				String str = sw.toString();
				AppLogs.logData  += "web认证中的异常信息:+" + e.toString() + "\n"+str +"\n";
			}
			System.out.println("CMCC------------------->登录返回结果：" + result);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (result.contains("loginrr.jpg") || result.contains("尊敬的用户")
						|| result.contains("您当前使用的套餐")) {
					System.err.println("登录成功！！！！！！！！！！！！！！");
					Global.logoutParascmcc = parseParamst(result, "input");// 获取下线参数
					Global.logoutUrlcmcc = logoutdo(result, "form", "action",
							"portal");
					/*
					 * Global.logoutParasToCMCC = logoutParas;
					 * Global.logoutUrlToCMCC = logoutUrl;
					 */
					isSuccess = true;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			isSuccess = false;
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw, true));
			String str = sw.toString();
			AppLogs.logData  += "web认证中的异常信息:+" + e.toString() + "\n"+str +"\n";
		}
			return isSuccess;
		
	}

	/**
	 * CMCC或者CMCC-EDU下线
	 * 
	 * @return
	 */
	public boolean logOut() {
		boolean isLogOutSuccess = false;
		if (wifiInfo != null && wifiInfo.getSSID() != null
				&& wifiInfo.getSSID().toLowerCase().equals("cmcc")) {// 对CMCC认证
			// isLogOutSuccess= logoutcmcc();
		} else if (wifiInfo != null && wifiInfo.getSSID() != null
				&& wifiInfo.getSSID().toLowerCase().equals("cmcc-edu")) {// 对CMCC-EDU认证
			// isLogOutSuccess= logout1();
		}
		return isLogOutSuccess;
	}

	/**
	 * CMCC下线
	 * 
	 * @return
	 */
	public void logoutcmcc() {
		new Thread() {
			public void run() {
				boolean sucess = false;
				try {

					HttpPost post = new HttpPost(Global.logoutUrlcmcc);
					post.setEntity(new UrlEncodedFormEntity(
							setlogoutRequestParams(Global.logoutParascmcc)));
					HttpResponse response = client.execute(post);
					int sc = response.getStatusLine().getStatusCode();
					String result = EntityUtils.toString(response.getEntity());
//					writeToSDcardFile("CMCC.txt",
//							"CMCC下线----------------------》" + result);
					System.out.println("下线页：" + result);
					if (sc == HttpStatus.SC_OK) {
						if (result.contains("下线成功")) {
							sucess = true;
							Global.logoutParascmcc = new HashMap<String, String>();
							Global.logoutUrlcmcc = new String();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					Message msg1 = new Message();
					if (sucess) {
						msg1.what = MessageWhat.LOGOUT_SUCCESS;
					} else {
						msg1.what = MessageWhat.LOGOUT_FAILED;
					}
					cmccHandler.sendMessage(msg1);
				}
			}
		}.start();
	}

	/**
	 * CMCC 下线参数的获取
	 * 
	 * @param mapParams
	 * @return
	 */
	private List<NameValuePair> setlogoutRequestParams(
			Map<String, String> mapParams) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("button2", "下  线"));
		params.add(new BasicNameValuePair("username", mapParams.get("username")));
		params.add(new BasicNameValuePair("backupInfo", mapParams
				.get("backupInfo")));
		params.add(new BasicNameValuePair("logintime", mapParams
				.get("logintime")));
		params.add(new BasicNameValuePair("remaintime", mapParams
				.get("remaintime")));
		params.add(new BasicNameValuePair("areacode", mapParams.get("areacode")));
		params.add(new BasicNameValuePair("wlanacip", mapParams.get("wlanacip")));
		params.add(new BasicNameValuePair("wlanacname", mapParams
				.get("wlanacname")));
		params.add(new BasicNameValuePair("wlanuserip", mapParams
				.get("wlanuserip")));
		params.add(new BasicNameValuePair("productid", mapParams
				.get("productid")));
		params.add(new BasicNameValuePair("effecttime", mapParams
				.get("effecttime")));
		params.add(new BasicNameValuePair("expiretime", mapParams
				.get("expiretime")));
		params.add(new BasicNameValuePair("keystr", mapParams.get("keystr")));
		params.add(new BasicNameValuePair("cf", mapParams.get("cf")));
		params.add(new BasicNameValuePair("logouttype", mapParams
				.get("logouttype")));
		params.add(new BasicNameValuePair("logonsessid", mapParams
				.get("logonsessid")));
		params.add(new BasicNameValuePair("portion", mapParams.get("portion")));
		params.add(new BasicNameValuePair("wlanacssid", mapParams
				.get("wlanacssid")));
		params.add(new BasicNameValuePair("uaId", mapParams.get("uaId")));
		params.add(new BasicNameValuePair("Token", mapParams.get("Token")));
		params.add(new BasicNameValuePair("passflag", mapParams.get("passflag")));
		params.add(new BasicNameValuePair("passtype", mapParams.get("passtype")));
		return params;
	}

	/**
	 * 获取的是下线的地址
	 * 
	 * @param content
	 * @param tag
	 * @param attr
	 * @param name
	 * @return
	 */
	private String logoutdo(String content, String tag, String attr, String name) {
		String logoutUrl = null;
		Document doc = Jsoup.parse(content);
		for (int i = 0; i < doc.select(tag).size(); i++) {
			Element e = doc.select(tag).get(i);
			if (name.equals(e.attr("name"))) {
				logoutUrl = e.attr(attr);
				break;
			}
		}
		return logoutUrl;
	}

	/**
	 * CMCC把MAP转换成List<NameValuePair>
	 * 
	 * @param mapParams
	 * @return
	 */
	private List<NameValuePair> setRequestParams(Map<String, String> mapParams) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("staticusername", userName));
		params.add(new BasicNameValuePair("staticpassword", passWord));
		params.add(new BasicNameValuePair("loginmode", mapParams
				.get("loginmode")));
		params.add(new BasicNameValuePair("wlanacip", mapParams.get("wlanacip")));
		params.add(new BasicNameValuePair("wlanacname", mapParams
				.get("wlanacname")));
		params.add(new BasicNameValuePair("wlanuserip", mapParams
				.get("wlanuserip")));
		params.add(new BasicNameValuePair("wlanacssid", mapParams
				.get("wlanacssid")));
		params.add(new BasicNameValuePair("portion", mapParams.get("portion")));
		params.add(new BasicNameValuePair("obsReturnAccount", mapParams
				.get("obsReturnAccount")));
		params.add(new BasicNameValuePair("uaId", mapParams.get("uaId")));
		params.add(new BasicNameValuePair("Token", mapParams.get("Token")));
		params.add(new BasicNameValuePair("button2", "登 录"));
		params.add(new BasicNameValuePair("sloginvalidate", "输入验证码"));
		params.add(new BasicNameValuePair("sloginhiddenvalidate", ""));
		params.add(new BasicNameValuePair("spid", ""));
		params.add(new BasicNameValuePair("sloginhiddenvalidate", mapParams
				.get("logonsessid")));
		return params;
	}

	/**
	 * 获取的是CMCC上线的地址
	 * 
	 * @param content
	 * @param tag
	 * @param attr
	 * @return
	 */
	private String logingdo(String content, String tag, String attr) {
		String loginUrl = null;
		Document doc = Jsoup.parse(content);
		Element e = doc.select(tag).last();
		if (e != null) {
			loginUrl = e.attr(attr);
		}
		return loginUrl;
	}

	/**
	 * CMCC上线获取参数
	 * 
	 * @param content
	 * @param tag
	 * @return
	 */
	private Map<String, String> parseParamst(String content, String tag) {
		Map<String, String> httpParams = new HashMap<String, String>();
		Document doc = Jsoup.parse(content);
		try {
			for (int i = 0; i < doc.select(tag).size(); i++) {
				Element e = doc.select(tag).get(i);
				// System.err.println("e:"+e.toString());
				String type = e.attr("type");
				if ("hidden".equals(type)) {
					String name = e.attr("name");
					String value = e.attr("value");
					System.err.println("id:" + name + "  value:" + value);
					httpParams.put(name, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpParams;
	}

	/**
	 * EDU下线
	 * 
	 * @return
	 */
	public boolean logout1() {
		String data = "";
		boolean sucess = false;
		HttpClient client = HttpUtils.getSSLHttpClient();
		if (Global.logoutUrl == null) {
			try {
				data += "地址为空\n";
				// writeToSDcardFile("logout.txt",data);
				System.out.println("----Updata----Updata----- >" + data);
			} catch (Exception e) {
				System.out.println("-----苏移动WEB认证下线打印----------- "
						+ e.toString());
			}
			return false;
		}

		HttpPost post = new HttpPost(
				"http://221.130.120.178:8080/logoutServlet");

		try {
			post.setEntity(new UrlEncodedFormEntity(
					setRequestParamsTOEDU(Global.logoutParas)));
			HttpResponse response = client.execute(post);
			int sc = response.getStatusLine().getStatusCode();
			String result = EntityUtils.toString(response.getEntity());
			// System.out.println("下线页："+result);
			data += "下线返回页:" + result + "\n";
			try {
				// writeToSDcardFile("logout.txt",data);
				System.out.println("----Updata----Updata----- >" + data);
			} catch (Exception e) {
				System.out.println("-----苏移动WEB认证下线打印----------- "
						+ e.toString());
			}
			if (sc == HttpStatus.SC_OK) {
				if (result.contains("下线成功")) {
					sucess = true;
					System.out.println("下线成功！！！！！！！！！！！！！！");
				}
			}
		} catch (Exception e) {
		}
		return sucess;
	}

	/**
	 * 给出一个Map 得到List<NameValuePair> 根据上线的参数，设置post请求参数的值
	 */
	private List<NameValuePair> setRequestParamsTOEDU(
			Map<String, String> mapParams) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		Set<Map.Entry<String, String>> set = mapParams.entrySet();
		for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it
					.next();
			String key = entry.getKey();
			String value = entry.getValue();
			params.add(new BasicNameValuePair(key, value));
		}
		return params;
	}

	/**
	 * 这个类是为了监听WEBView
	 * 
	 * @author ls
	 * 
	 */
	final class MyWebViewClient extends WebViewClient {
//		public boolean shouldOverrideUrlLoading(WebView view, String url) {
//			view.loadUrl(url);
//			return true;
//		}

		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d("WebView", "onPageStarted");
			System.out.println("------+++++++++++--------------------++++++++++=");
			super.onPageStarted(view, url, favicon);
		}

		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			Log.d("WebView", "onPageFinished ");
			view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
					+ "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
		}
	}

	/**
	 * 打印的是WEB访问的网址，返回的网页代码
	 * 
	 * @author ls
	 * 
	 */
	final class InJavaScriptLocalObj {
		public void showSource(String html) {
			Log.d("HTML", html);
			AuthString = html;
			Global.AuthString = AuthString;
 
			loadAurhEndTime = System.currentTimeMillis();
			loadAuthTime = (loadAurhEndTime - loadAuthStartTime) / (float)1000;			
			
			if (isFirst) {//webview未加载成功时，会重新加载，重新发message
				isFirst = false;
				Message msg = new Message();
				msg.arg1 = MessageWhat.BAIDU_LOADED;
				mhandler.sendMessage(msg);
			}
			
		}
	}

	public float getLoadAuthTime() {
		return loadAuthTime;
	}

	public void setLoadAuthTime(long loadAuthTime) {
		this.loadAuthTime = loadAuthTime;
	}

	 

}
